import {readHtmlFile} from './utils'
import * as step from '@flow-step/step-toolkit'
import cheerio from 'cheerio'
import {Issue} from '@flow-step/step-toolkit/src/redline'
import * as fs from 'fs'
import {IParams} from './params'
import path from 'path'


export async function parseAndUploadReport(reportPath:string,params:IParams){
    step.info('start to parse and upload report')
    const data = await readHtmlFile(reportPath)
    step.debug('original html content:')
    step.debug(data)
    const issue = count(data)
    const updateHtml = modifyHtml(data)

    const tmpDir = path.join(params.projectDir,'tmp')
    if (!fs.existsSync(tmpDir)){
        fs.mkdirSync(tmpDir)
    }
    const targetPath = path.join(tmpDir,path.basename(reportPath))
    if (fs.existsSync(targetPath)){
        fs.unlinkSync(targetPath)
    }
    fs.writeFileSync(targetPath,updateHtml)

    await step.redline.outputCodeScanResult(
        {
            reportLocalPath: targetPath,
            issue: issue,
        },
        params.redline
    )
}

export function modifyHtml(htmlContent: string) {
    const $ = cheerio.load(htmlContent);
    $('td h2').first().text("The code scan report of Alibaba Java Coding Guidelines(Implemented by PMD rules).");
    $('div.p1').first().text('Blocker');
    $('div.p2').first().text('Critical');
    $('div.p3').first().text('Major');
    $('div.p4').first().text('Minor');
    $('div.p5').first().text('Info');
    $('title').first().text("The code scan report of Alibaba Java Coding Guidelines(Implemented by PMD rules).");
    $('title').first().after('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
    const updatedHtml = $.html();
    return updatedHtml
}

export function count(htmlContent: string): Issue{
    const $ = cheerio.load(htmlContent)
    let res = {
        total : 0,
        blocker: 0,
        critical: 0,
        major: 0,
    } as Issue

    $('tr.a > td').each((index: number, element: any) => {
    switch (index) {
        case 1:
            res.total = parseInt($(element).text(),10)
            break
        case 2:
            res.blocker = parseInt($(element).text(),10)
            break
        case 3:
            res.critical = parseInt($(element).text(),10)
            break
        case 4:
            res.major = parseInt($(element).text(),10)
            break
        }
    })
    return res
}